package com.learn.util;

/**
 * CRC Util
 */
public class CRCUtil {
    /**
     * CRC16 CCITT XMODEM<br>
     * 多项式x16+x12+x5+1（0x1021），初始值0x0000，低位在后，高位在前
     */
    public static short getCrc16Xmodem(byte[] bytes) {
        int crc = 0x00; // initial value -- CRC-CCITT (XModem)
        int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)

        for (byte b : bytes) {
            for (int i = 0; i < 8; i++) {
                boolean bit = ((b >> (7 - i) & 1) == 1);
                boolean c15 = ((crc >> 15 & 1) == 1);
                crc <<= 1;
                if (c15 ^ bit)
                    crc ^= polynomial;
            }
        }

        crc &= 0xffff;

        return (short) crc;
    }
}